package com.ruoyi.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.core.web.page.TableSupport;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.Leaves;
import com.ruoyi.system.domain.vo.LeavesVo;
import com.ruoyi.system.service.LeavesService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/applys")
public class LeaveController extends BaseController {
    @Autowired
    LeavesService leavesService;
    @Autowired
    RuntimeService runtimeService;
    @Autowired
    TaskService taskService;
    @Autowired
    HistoryService historyService;
    @JsonIgnore
    List<LeavesVo> arrayList;


    @JsonIgnore
    public List<LeavesVo> getArrayList() {
        return arrayList;
    }
    /**
     * 获取请假列表
     */
    @GetMapping("/list")
    @RequiresPermissions("note:applys:list")
    public TableDataInfo list(Leaves leaves)
    {
        Page<Leaves> page = new Page<>();
        page.setCurrent(Convert.toInt(ServletUtils.getParameter(TableSupport.PAGE_NUM), 1));
        page.setSize(Convert.toInt(ServletUtils.getParameter(TableSupport.PAGE_SIZE), 10));
        String leaveName = SecurityUtils.getUsername();
        page = leavesService.selectPageVo(page,leaves,leaveName);
        return getDataTable(page.getRecords(),page.getTotal());
    }



    @GetMapping("/task")
    public List<LeavesVo> task()
    {
        String username = SecurityUtils.getUsername();
        arrayList = new ArrayList<>();
        List<Task> list = taskService.createTaskQuery().taskAssignee(username).list();
        for (Task task : list) {
            String instanceId = task.getProcessInstanceId();
            LeavesVo leavesVo = new LeavesVo();
            leavesVo.setTaskId(task.getId());
            leavesVo.setTaskName(task.getName());
            leavesVo.setTaskAssignee(task.getAssignee());
            leavesVo.setInstanceId(instanceId);
            ProcessInstance result = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).singleResult();
            String businessKey = result.getBusinessKey();
            Leaves leaves = leavesService.getById(businessKey);
            leavesVo.setLeaveId(leaves.getLeaveId());
            leavesVo.setLeaveName(leaves.getLeaveName());
            leavesVo.setTitle(leaves.getTitle());
            leavesVo.setDays(leaves.getDays());
            leavesVo.setStartTime(leaves.getStartTime());
            leavesVo.setEndTime(leaves.getEndTime());
            leavesVo.setReason(leaves.getReason());
            leavesVo.setRemark(leaves.getRemark());
            leavesVo.setProposer(leaves.getProposer());
            leavesVo.setLeaveImg(leaves.getLeaveImg());
            leavesVo.setStatus(leaves.getStatus());
            leavesVo.setCreateBy(leaves.getCreateBy());
            leavesVo.setCreateTime(leaves.getCreateTime());
            leavesVo.setUpdateBy(leaves.getUpdateBy());
            leavesVo.setUpdateTime(leaves.getUpdateTime());
            arrayList.add(leavesVo);
        }
        return arrayList;
    }

    @PostMapping("complete")
    public void complete(@RequestBody LeavesVo leavesVo){
        HashMap<String, Object> map = new HashMap<>();
        map.put("days",leavesVo.getDays());
        map.put("flag",leavesVo.getFlag());
        taskService.complete(leavesVo.getTaskId(),map);
    }

    @GetMapping("goApply")
//    public AjaxResult goApply(@PathVariable String procId,@PathVariable(required = false) String proposer,@PathVariable Long days,@PathVariable String flag
//    ){
    public AjaxResult goApply(@RequestParam(value = "procId",required = false) String procId,
                              @RequestParam(value = "proposer",required = false) String proposer,
                              @RequestParam(value = "days",required = false) Long days,
                              @RequestParam(value = "flag",required = false) String flag
    ){
        System.err.println(procId);
        System.err.println(proposer);
        System.err.println(days);
        System.err.println(flag);
        AjaxResult ajax = AjaxResult.success();
        HashMap<String, Object> map = new HashMap<>();
        Task task = taskService.createTaskQuery().processInstanceId(procId).taskAssignee(SecurityUtils.getUsername()).singleResult();
        map.put("person",proposer);
        map.put("days",days);
        map.put("flag",flag);
        taskService.complete(task.getId(),map);
        Leaves one = leavesService.getOne(Wrappers.lambdaQuery(Leaves.class).eq(Leaves::getProcId, procId));
        if("总经理".equals(task.getName()) && one.getDays()>=3){
            leavesService.update(Wrappers.lambdaUpdate(Leaves.class).set(Leaves::getStatus,"2").eq(Leaves::getProcId,procId));
        }
        if(flag.equals("1")){
            leavesService.update(Wrappers.lambdaUpdate(Leaves.class).set(Leaves::getStatus,"4").eq(Leaves::getProcId,procId));
        }
        else if("项目经理".equals(task.getName()) && one.getDays()<=3){
            leavesService.update(Wrappers.lambdaUpdate(Leaves.class).set(Leaves::getStatus,"2").eq(Leaves::getProcId,procId));
        } else{
            leavesService.update(Wrappers.lambdaUpdate(Leaves.class).set(Leaves::getStatus,"1").eq(Leaves::getProcId,procId));
        }
        return ajax;
    }

    @GetMapping("listActivity")
    public TableDataInfo listActivity(){
        List<Leaves> leavesList = new ArrayList<>();
        List<Task> list = taskService.createTaskQuery().processDefinitionKey("qingjia")
                .taskAssignee(SecurityUtils.getUsername())
                .list();
        for (Task task : list) {
            ProcessInstance result = runtimeService
                    .createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId()).singleResult();
            String businessKey = result.getBusinessKey();
            Leaves leaves = leavesService.getById(businessKey);
            leavesList.add(leaves);
        }
        return getDataTable(leavesList);
    }

    /**
     * 新增请假单
     */
    @PostMapping
    @RequiresPermissions("note:applys:add")
    public AjaxResult add(@RequestBody Leaves leaves)
    {
        leaves.setCreateTime(new Date());
        leaves.setCreateBy(SecurityUtils.getUsername());
        boolean save = leavesService.save(leaves);
        if(save){
            HashMap<String, Object> map = new HashMap<>();
            map.put("person",SecurityUtils.getUsername());
            ProcessInstance qingjia = runtimeService.startProcessInstanceByKey("qingjia", leaves.getLeaveId() + "", map);
            String id = qingjia.getId();
            leaves.setProcId(id);
            leavesService.updateById(leaves);
        }
        return success();
    }

    /**
     * 根据请假单编号获取详细信息
     */
    @GetMapping(value = { "/", "/{leaveId}" })
    public AjaxResult getInfo(@PathVariable(value = "leaveId", required = false) Long leaveId)
    {
        return success(leavesService.getById(leaveId));
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("note:applys:edit")
    @PutMapping
    public AjaxResult edit(@RequestBody Leaves leaves)
    {
        leaves.setUpdateTime(new Date());
        leaves.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(leavesService.updateById(leaves));
    }
    @RequiresPermissions("note:applys:remove")
    @DeleteMapping("/{leaveIds}")
    public AjaxResult remove(@PathVariable Long[] leaveIds)
    {
        return toAjax(leavesService.removeBatchByIds(Arrays.asList(leaveIds)));
    }

    @GetMapping("/history")
    public List<LeavesVo> history()
    {
        String username = SecurityUtils.getUsername();
        arrayList = new ArrayList<>();
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        List<HistoricTaskInstance> list = processEngine.getHistoryService()
                .createHistoricTaskInstanceQuery()
                .taskAssignee(username)
                .finished()
                .list();
        for (HistoricTaskInstance historicTaskInstance : list) {
            LeavesVo leavesVo = new LeavesVo();
            leavesVo.setTaskId(historicTaskInstance.getId());
            leavesVo.setTaskName(historicTaskInstance.getName());
            leavesVo.setTaskAssignee(historicTaskInstance.getAssignee());
            leavesVo.setStartTime(historicTaskInstance.getStartTime());
            leavesVo.setEndTime(historicTaskInstance.getEndTime());
            System.err.println(JSON.toJSONString(historicTaskInstance));
            arrayList.add(leavesVo);
        }
        return arrayList;
    }
}
